<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>jsonp</title>
  </head>
  <body>
    <script>
      // 实现jsonp
      // script标签不遵循同源协议，可以用来进行跨域请求，优点就是兼容性好但仅限于GET请求
      const jsonp = (url, data = {}, cb = "callback") => {
        let searchStr = url.indexOf("?") === -1 ? "?" : "&";
        for (const key in data) {
          searchStr += `${key}=${data[key]}&`;
        }
        searchStr += `callback=${cb}`;
        url = url + searchStr;

        const script = document.createElement("script");
        script.src = url;
        document.body.appendChild(script); // append 到页面中添加到页面就立刻发起请求

        return new Promise((resolve, reject) => {
          window[cb] = (data) => {
            try {
              resolve(data);
            } catch (error) {
              reject(error);
            } finally {
              script.parentNode.removeChild(script); // 移除 script
            }
          };
        });
      };
      // 测试
      jsonp('https://jsonplaceholder.typicode.com/todos/1', {}).then((res) => {
        console.log(res);
      });
    </script>
  </body>
</html>
